<?php

namespace app\resources\tasks;

use think\facade\Cache;
use app\resources\model\WebSocket;


// app('swoole.server')->task([ PushTask::class, [
//     'uid'=>2,
//     'msg'=>[
//         'type'=>1,
//         'data'=>'asdsada'
//     ]
// ]]);

// ws://127.0.0.1:5375/ws?action=web&token=eyJ0eXAiOiJKV1Qi

// 推送 websocket 消息

class PushTask
{

    protected $params = [];
    protected $ws;

    public function __construct($params = [])
    {
        $this->params = $params;
        $this->ws = app('\think\swoole\Websocket');
        if (($this->params['_action'] ?? '') != 'reset') {
            $this->start();
        }
    }

    // 发送
    public function start()
    {
        $uid = $this->params['uid'];
        $msg = $this->params['msg'] ?: [];
        $fds = WebSocket::where('uid',$uid)->column('fd');
        if($fds){
            // 在线
            foreach($fds as $fd){
                $this->ws->to($fd)->push(json_encode($msg, true));
            }
        } else {
            // 离线
            Cache::push('PushTask', json_encode($this->params,true) );
        }
    }

    // 离线消息上线后重发
    public function reset($fd)
    {
        $pushTask = Cache::get('PushTask');
        if($pushTask){
            Cache::delete('PushTask');
            foreach($pushTask as $task){
                $params  = json_decode($task,true);
                if($params['uid'] ?? ''){
                    $fd = Cache::store('redis')->hget('WebSocket', $params['uid'] );
                    if($fd){
                        new self($params);
                        new self($params);
                    }else{
                        Cache::push('PushTask', $task );
                    }
                }
            }
        }
    }
}
